package com.fr.elastic;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

/**
 * @author 付荣
 * @version 创建时间：2018年5月10日 下午1:43:33
 */
public class HotelIndexTest {
	private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
	private static TransportClient client = null;
	static {
		try {
			client = TransportClient.builder().settings(Settings.builder().put("cluster.name", "lmm_ultimate_search").build()).build()
					.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.0.55"), 9300))
					.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("10.200.2.95"), 9300))
					.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("10.200.2.79"), 9300));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
//		createIndex();
		insert();
	}

	private static void createIndex() {
		CreateIndexRequest createRequest = new CreateIndexRequest("hotel_test_fr");
		Settings.Builder settingsBuilder = Settings.settingsBuilder();
		settingsBuilder.put("number_of_shards", 3) // 设置分片数量
				.put("number_of_replicas", 1); // 设置副本数量
		createRequest.settings(settingsBuilder);

		client.admin().indices().create(createRequest).actionGet();
	}

	private static void insert() {
		BulkRequestBuilder bulkRequest = client.prepareBulk();
		for (int i = 0; i < 200000; i++) {
			bulkRequest.add(client.prepareIndex("hotel_test_fr", "hotel_test_fr").setSource(createSource(i)));
			if (i % 1000 == 0) {
				bulkRequest.get();
				bulkRequest = client.prepareBulk();
			}
		}
		bulkRequest.get();
	}

	private static Map<String, Object> createSource(int i) {
		Map<String, Object> map = new HashMap<>();
		map.put("id", i);
		Calendar c1 = Calendar.getInstance();
		for (int j = 0; j < 180; j++) {
			String begin = simpleDateFormat.format(c1.getTime());
			Calendar c2 = Calendar.getInstance(c1.getTimeZone());
			for (int k = 0; k < 20; k++) {
				c2.add(Calendar.DAY_OF_YEAR, 1);
				String key = "timePrice" + begin + simpleDateFormat.format(c2.getTime());
				map.put(key, Math.random());
			}
			c1.add(Calendar.DAY_OF_YEAR, 1);
		}
		return map;
	}

}
